package com.arron.ioAndNio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Classname TestNonBlockingNioServer
 * @Date 2020/8/28 1:28
 * @Created by 刘
 */
public class TestNonBlockingNioServer {

    public static void main(String[] args) throws IOException {

        //创建套接字
        ServerSocketChannel open = ServerSocketChannel.open();
        //拿到通道
        ServerSocketChannel socketChannel = open.bind(new InetSocketAddress(8080));

        //开启非阻塞模式
        socketChannel.configureBlocking(false);

        //获取选择器
        Selector selector = Selector.open();
        //注册通道到选择器中,并指定监听事件
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //轮询式获取选择器中已准备就绪的事件
        while (selector.select()>0){

            //获取选择器上所有注册的选择键（已经就绪的监听事件）
            Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();

            while (selectionKeyIterator.hasNext()){
                SelectionKey key = selectionKeyIterator.next();
                //判断是什么事件准备就绪
                if (key.isAcceptable()){
                    System.out.println("一个客户端连接进入。。。。。");
                    //获取客户端连接通道
                    SocketChannel accept = socketChannel.accept();
                    //同样开启非阻塞模式
                    accept.configureBlocking(false);
                    //注册到选择器中,并指定读事件
                    accept.register(selector,SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    System.out.println("准备读取客户端数据。。。");
                    //准备读
                    //获取选择器上准备读的通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    int len = 0;
                    while ((len = channel.read(buffer))>0){
                        buffer.flip();
                        String s = new String(buffer.array(), 0, len);
                        System.out.println(s);
                        buffer.clear();
                    }

                }

                //移除选择键
                selectionKeyIterator.remove();

            }


        }

    }



}
